package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.DefaultRopClient;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.PageTreeUI;
import com.taotao.admin.pojo.TreeUI;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.BaseDomain;
import com.taotao.rop.database.domain.WechatArticle;
import com.taotao.rop.database.domain.WechatMenu;
import com.taotao.rop.response.BaseResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = "/wechat/article")
public class WechatArticleController {
    private final String imgFolder = "wechatArticles";
    private final String descImgFolder = "/opt/cmcc_root/webapps/" + imgFolder;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object getList(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(new BaseDomain(), BaseResponse.class, "wechatArticle.list", "1.0");
        return setArticleResponse(response);
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    @ResponseBody
    public Object getPageList(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Long pageSize = Long.parseLong(request.getParameter("pageSize"));
        Long pageNo = Long.parseLong(request.getParameter("pageNo"));

        WechatArticle condition = new WechatArticle();
        condition.setPageNo(pageNo);
        condition.setPageSize(pageSize);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "wechatArticle.pageList", "1.0");
        Object result = setArticleResponse(response);
        if (result instanceof List) {
            List<TreeUI> resultList = (List<TreeUI>) result;
            BaseResponse respMenu = response.getSuccessResponse();
            PageTreeUI pageTreeUI = new PageTreeUI();
            pageTreeUI.setTotal(respMenu.getMsg());
            pageTreeUI.setRows(resultList);
            return pageTreeUI;
        } else {
            return result;
        }
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        WechatArticle article = null;
        try {
            article = getArticleFromRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (article != null) {
            CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                    .post(article, BaseResponse.class, "wechatArticle.insert", "1.0");
            if (response.isSuccessful()) {
                return response.getSuccessResponse();
            } else {
                return response.getErrorResponse().getSubErrors().get(0);
            }
        } else {
            BaseResponse resp = new BaseResponse();
            resp.setMsg("输入有误，请核对");
            return resp;
        }
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        WechatArticle article = null;
        try {
            article = getArticleFromRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (article != null) {
            article.setId(Long.parseLong(id));
            CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                    .post(article, BaseResponse.class, "wechatArticle.update", "1.0");
            if (response.isSuccessful()) {
                return response.getSuccessResponse();
            } else {
                return response.getErrorResponse().getSubErrors().get(0);
            }
        } else {
            BaseResponse resp = new BaseResponse();
            resp.setMsg("输入有误，请核对");
            return resp;
        }
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        WechatMenu menu = new WechatMenu();
        menu.setId(Long.parseLong(id));
        menu.setStatus(Constant.STATUS_DELETE);
        DefaultRopClient ropClient = MyRopClient.getRopClient(request.getHeader("sessionId"));
        CompositeResponse<BaseResponse> response = ropClient.buildClientRequest()
                .post(menu, BaseResponse.class, "wechatArticle.update", "1.0");
        if (response.isSuccessful()){
            return response.getSuccessResponse();
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = {MediaType.TEXT_HTML_VALUE})
    @ResponseBody
    public Object uploadFile(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        String fileName = UUID.randomUUID().toString() + ".png";
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try{
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                File descFolder = new File(descImgFolder);
                if (!descFolder.exists()) {
                    descFolder.mkdirs();
                }
                File file = new File(descImgFolder, fileName);
                file.setWritable(true);
                item.write(file);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return String.format("{msg:'%s'}", "");
        }

        return String.format("{msg:'%s'}", imgFolder + "/" + fileName);
    }

    private Object setArticleResponse(CompositeResponse<BaseResponse> response) {
        if (response.isSuccessful()) {
            BaseResponse respMenu = response.getSuccessResponse();
            if (respMenu.getSuccess()) {
                List<TreeUI> allTreeUI = new ArrayList<TreeUI>();
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) respMenu.getData();
                for (LinkedHashMap<String, Object> data : respData) {
                    List<LinkedHashMap<String, Object>> subTree = (List<LinkedHashMap<String, Object>>) data.get("subArticleList");
                    TreeUI treeUI = new TreeUI();
                    treeUI.setId(Long.parseLong(data.get("id").toString()));
                    treeUI.setText(data.get("title").toString());
                    treeUI.setTitle(data.get("title").toString());
                    List<TreeUI> children = new ArrayList<TreeUI>();
                    for (LinkedHashMap<String, Object> sub : subTree) {
                        TreeUI child = new TreeUI();
                        child.setId(Long.parseLong(sub.get("id").toString()));
                        child.setText(sub.get("title").toString());
                        child.setTitle(sub.get("title").toString());
                        if (sub.get("description") != null) {
                            child.setDescription(sub.get("description").toString());
                        }
                        if (sub.get("picUrl") != null) {
                            child.setPicUrl(sub.get("picUrl").toString());
                        }
                        if (sub.get("url") != null) {
                            child.setUrl(sub.get("url").toString());
                        }
                        if (sub.get("appId") != null) {
                            child.setAppId(sub.get("appId").toString());
                        }
                        child.setParentId(Long.parseLong(sub.get("parentId").toString()));
                        child.setSort(Integer.parseInt(sub.get("sort").toString()));
                        child.setStatus(Integer.parseInt(sub.get("status").toString()));
                        children.add(child);
                    }
                    treeUI.setChildren(children);
                    if (children.size() > 0) {
                        treeUI.setState("closed");
                    } else {
                        treeUI.setState("open");
                    }
                    if (data.get("description") != null) {
                        treeUI.setDescription(data.get("description").toString());
                    }
                    if (data.get("picUrl") != null) {
                        treeUI.setPicUrl(data.get("picUrl").toString());
                    }
                    if (data.get("url") != null) {
                        treeUI.setUrl(data.get("url").toString());
                    }
                    if (data.get("appId") != null) {
                        treeUI.setAppId(data.get("appId").toString());
                    }
                    treeUI.setParentId(Long.parseLong(data.get("parentId").toString()));
                    treeUI.setSort(Integer.parseInt(data.get("sort").toString()));
                    treeUI.setStatus(Integer.parseInt(data.get("status").toString()));
                    allTreeUI.add(treeUI);
                }
                return allTreeUI;
            } else {
                return respMenu;
            }
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    private WechatArticle getArticleFromRequest(HttpServletRequest request) throws Exception{
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String picUrl = request.getParameter("picUrl");
        String url = request.getParameter("url");
        String parentId = request.getParameter("parentId");
        String appId = request.getParameter("appId");
        String sort = request.getParameter("sort");
        String status = request.getParameter("status");

        WechatArticle article = new WechatArticle();
        article.setTitle(title);
        article.setDescription(description);
        article.setPicUrl(picUrl);
        article.setUrl(url);
        article.setParentId(Long.parseLong(parentId));
        article.setAppId(appId);
        if (sort != null) {
            article.setSort(Integer.parseInt(sort));
        }
        article.setStatus(Integer.parseInt(status));
        return article;
    }
}
